package com.zito.manager;

import java.io.File;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.downlove.common.RequestContext;
import com.downlove.database.QueryHelper;
import com.zito.ErrMsgException;
import com.zito.bean.Article;
import com.zito.bean.Articlefiles;
import com.zito.common.Paginator;

/**
 * @author YunHai-Home
 * 
 */
public class PartyBuildingManager{

	private Paginator paginator;
	private final Logger logger = LoggerFactory
			.getLogger(PartyBuildingManager.class);
	
	/**
	 * 分页
	 * @return
	 */
	public String getPaginator() {
		return this.paginator.getCssPageBlock();
	}

	public Paginator getPaginatorBean() {
		return this.paginator;
	}
	
	 /**
     * 查询机关党建专版电子版列表
     * @throws ErrMsgException 
     */
	@SuppressWarnings("unchecked")
	public List<Article> partybuildingList(int pagesize) throws ErrMsgException {
		RequestContext rc = RequestContext.get();
		Article article = new Article();
		String filter = " columnid = 13 ";
	    int total = article.TotalCount(filter);
		this.paginator = new Paginator(rc, total, pagesize);
		// 设置当前页数和总页数
		int totalpages = this.paginator.getTotalPages();
		int curpage = this.paginator.getCurrentPage();
		if (totalpages == 0) {
			curpage = 1;
			totalpages = 1;
		}
		List<Long> tmpList = article.idListFilter(filter, curpage, pagesize);
		return article.LoadList(tmpList);
	}
	

	/**
	 * 根据ID 获取页面详细
	 * @return
	 * @throws ErrMsgException
	 */
	public Article getPartyBuilding() throws ErrMsgException {
		RequestContext rc = RequestContext.get();
		Article article = new Article();
		Long id = rc.param("id", -1L);
		article = article.Get(id);
		return article;
	}

	/**
	 * 新增、编辑
	 * @return
	 * @throws ErrMsgException
	 * @throws IOException
	 */
	public boolean operatingPost() throws ErrMsgException, IOException {
		RequestContext rc = RequestContext.get();
		Article obj = new Article();
		long tempid = rc.param("id", -1); 
		obj = obj.Get(tempid);
		return obj == null ? insertPartyBuilding(rc) : editPartyBuilding(rc);
	}

	/**
	 * 新增机关党建专版电子版列表
	 * @param rc
	 * @return
	 * @throws ErrMsgException
	 * @throws IOException
	 */
	public boolean insertPartyBuilding(RequestContext rc)
			throws ErrMsgException, IOException {
		Article article = new Article();
		article = rc.form(Article.class); //获取form的内容
    	String error = article.doValidator();//验证
		if (!StringUtils.isBlank(error))
			throw new ErrMsgException(error);
		article.setType(0);
		article.setStatus(0);
		article.setColumnid(13L);
		article.setSpecialid(-1l);
		article.setAuthor(MasterSession.get().getUserName());
		article.setAuthorid(MasterSession.get().getUserID());
 		return article.Save(RequestContext.get().session().getId()) != -1L;//POJO
	}
	
	/**
	 * 编辑机关党建专版电子版列表
	 * @param rc
	 * @return
	 */
	private boolean editPartyBuilding(RequestContext rc) 
			throws ErrMsgException, IOException{
		Article article = new Article();
		article = rc.form(Article.class);
		if (article.getId() == -1)
			return false;
		String error = article.doValidator();
		if (!StringUtils.isBlank(error))
			throw new ErrMsgException(error);
		return article.Update(RequestContext.get().session().getId(),
				"title", "content", "postdate", "id") != -1L;
	}

	/**
	 * 删除机关党建专版电子版
	 * @return
	 * @throws ErrMsgException
	 */
	public boolean deletePartyBuilding() throws ErrMsgException {
		RequestContext rc = RequestContext.get();
		Article article = new Article();
      	ArticlefilesManager file = new ArticlefilesManager();
		article = rc.form(Article.class);
		if (article.getId() == -1)
			return false;
		List<String> paths = new ArrayList<String>();
		
		// 首先根据ID列出所有附件数据
		List<?> files = file.list(article.getId().intValue());
		for (Object afile : files) {
			Articlefiles tmp = (Articlefiles) afile;
			paths.add(tmp.getFileserverpath());
		}

		// 采用事务删除数据，先删除图片及附件数据，后删除该文章信息
       	String deleteFiles = "DELETE FROM articlefiles WHERE articleid=?";
		String deleteArticle = "DELETE FROM article WHERE id=?";
		boolean flag = true;
		try {
			QueryHelper.setAutoCommit();
        	QueryHelper.commitUpdate(deleteFiles, article.getId());
			QueryHelper.commitUpdate(deleteArticle, article.getId());
			QueryHelper.commit();
		} catch (Exception e) {
			flag = false;
			try {
				QueryHelper.rollback();
			} catch (SQLException e1) {
				logger.error("删除文章时出现异常：{}", e1.getMessage());
				throw new ErrMsgException("删除文章时出现异常，请联系管理员！" + e1.getMessage());
			}
			logger.error("删除文章时出现异常：{}", e.getMessage());
			throw new ErrMsgException("删除文章时出现异常，请联系管理员！" + e.getMessage());
		} finally {
			try {
				QueryHelper.closeTransConnection();
			} catch (SQLException e2) {
				logger.error("删除文章时出现异常：{}", e2.getMessage());
				throw new ErrMsgException("删除文章时出现异常，请联系管理员！" + e2.getMessage());
			}
		}
		// 数据删除成功后删除硬盘上文件,无论文件是否存在，在删除时不返回任何异常
		if (flag) {
			for (String path : paths) {
				FileUtils.deleteQuietly(new File(RequestContext.root() + path));
			}
		}
		return true;
	}	
}
